<template>
  <div>
    <!-- 主体 -->
    <div>
      <!-- 查询 -->
      <div class="form">
        <div class="fs-3" @click="router.push('/')">足球俱乐部</div>
        <div>
          <NForm inline>
            <NFormItem>
              <NSelect
                v-model:value="selectOptions.value"
                :options="selectOptions.options"
                :consistent-menu-width="false"
              ></NSelect>
            </NFormItem>

            <NFormItem>
              <NInput v-model:value="queryInfo.tname" placeholder="请输入球队名称"></NInput>
            </NFormItem>
            <NFormItem>
              <NInput v-model:value="queryInfo.league" placeholder="请输入联赛名称"></NInput>
            </NFormItem>

            <NFormItem>
              <NSpace>
                <NButton type="info" @click="requery">查询</NButton>
                <NButton type="error" @click="reset">重置</NButton>
                <NButton type="primary" @click="showAdd">添加</NButton>
              </NSpace>
            </NFormItem>
          </NForm>
        </div>
      </div>

      <!-- 表格 -->
      <div>
        <NDataTable :loading="queryLoading" :data="list" :columns="listColumns"></NDataTable>
      </div>

      <!-- 分页 -->
      <div class="page">
        <NFlex justify="center">
          <NPagination
            v-model:page="queryInfo.pageNumber"
            :page-size="queryPage.pageSize"
            :item-count="queryPage.total"
            @update-page="query"
          ></NPagination>
        </NFlex>
      </div>
    </div>

    <!-- 弹框部分 -->
    <div>
      <!-- add -->
      <div>
        <NModal v-model:show="addVisible" title="添加足球俱乐部" preset="dialog">
          <div>
            <NForm
              label-placement="left"
              size="small"
              require-mark-placement="right-hanging"
              label-width="auto"
            >
              <NFormItem label="俱乐部名称">
                <NInput v-model:value="addInfo.tname" placeholder="请输入俱乐部名称"></NInput>
              </NFormItem>

              <NFormItem label="俱乐部所属联赛">
                <NInput v-model:value="addInfo.league" placeholder="请输入俱乐部所属联赛"></NInput>
              </NFormItem>

              <NFormItem label="俱乐部简介">
                <NInput
                  type="textarea"
                  v-model:value="addInfo.intro"
                  placeholder="请输入俱乐部简介"
                ></NInput>
              </NFormItem>

              <NFormItem label="联赛冠军数">
                <NInputNumber
                  v-model:value="addInfo.champions"
                  button-placement="both"
                  min="0"
                ></NInputNumber>
              </NFormItem>

              <NFormItem label="杯赛冠军数">
                <NInputNumber
                  v-model:value="addInfo.cups"
                  button-placement="both"
                  min="0"
                ></NInputNumber>
              </NFormItem>

              <NFormItem label="粉丝数（万）">
                <NInputNumber
                  v-model:value="addInfo.fans"
                  button-placement="both"
                  :min="1"
                  placeholder="粉丝数至少为1"
                ></NInputNumber>
              </NFormItem>

              <NFormItem label="进球记录数">
                <NInputNumber
                  v-model:value="addInfo.goals"
                  button-placement="both"
                  :min="1"
                  placeholder="进球数至少为1"
                ></NInputNumber>
              </NFormItem>

              <NFormItem label="进球记录保持者">
                <NInput v-model:value="addInfo.gname" placeholder="请输入进球记录保持者"></NInput>
              </NFormItem>

              <NFormItem label="创建时间">
                <NDatePicker
                  value-format="yyyy-MM-dd"
                  v-model:formatted-value="dateinfo"
                  :is-date-disabled="dateValidate"
                ></NDatePicker>
              </NFormItem>
            </NForm>
          </div>

          <template #action>
            <NSpace>
              <NButton type="primary" @click="add" :loading="addLoading">确定添加</NButton>
            </NSpace>
          </template>
        </NModal>
      </div>

      <!-- modify -->
      <div>
        <NModal
          v-model:show="modifyVisible"
          title="修改足球俱乐部信息"
          preset="dialog"
          type="warning"
        >
          <div>
            <NForm
              label-placement="left"
              size="small"
              require-mark-placement="right-hanging"
              label-width="auto"
            >
              <NFormItem label="俱乐部名称">
                <NInput v-model:value="modifyInfo.tname" placeholder="请输入俱乐部名称"></NInput>
              </NFormItem>

              <NFormItem label="俱乐部所属联赛">
                <NInput
                  v-model:value="modifyInfo.league"
                  placeholder="请输入俱乐部所属联赛"
                ></NInput>
              </NFormItem>

              <NFormItem label="俱乐部简介">
                <NInput
                  type="textarea"
                  v-model:value="modifyInfo.intro"
                  placeholder="请输入俱乐部简介"
                ></NInput>
              </NFormItem>

              <NFormItem label="联赛冠军数">
                <NInputNumber
                  v-model:value="modifyInfo.champions"
                  button-placement="both"
                  min="0"
                ></NInputNumber>
              </NFormItem>

              <NFormItem label="杯赛冠军数">
                <NInputNumber
                  v-model:value="modifyInfo.cups"
                  button-placement="both"
                  min="0"
                ></NInputNumber>
              </NFormItem>

              <NFormItem label="粉丝数（万）">
                <NInputNumber
                  v-model:value="modifyInfo.fans"
                  button-placement="both"
                  :min="1"
                  placeholder="粉丝数至少为1"
                ></NInputNumber>
              </NFormItem>

              <NFormItem label="进球记录数">
                <NInputNumber
                  v-model:value="modifyInfo.goals"
                  button-placement="both"
                  :min="1"
                  placeholder="进球数至少为1"
                ></NInputNumber>
              </NFormItem>

              <NFormItem label="进球记录保持者">
                <NInput
                  v-model:value="modifyInfo.gname"
                  placeholder="请输入进球记录保持者"
                ></NInput>
              </NFormItem>

              <NFormItem label="创建时间">
                <NDatePicker
                  value-format="yyyy-MM-dd"
                  v-model:formatted-value="dateinfo"
                  :is-date-disabled="dateValidate"
                ></NDatePicker>
              </NFormItem>
            </NForm>
          </div>

          <template #action>
            <NSpace>
              <NButton type="warning" @click="modify" :loading="modifyLoading">保存</NButton>
            </NSpace>
          </template>
        </NModal>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Api } from '@/types/Api'
import type { BaseDataResult, BaseResult, PageBean, PageVO } from '@/types/BaseResult'
import type { TbFootballTeam } from '@/types/crud'
import { h, onMounted, ref } from 'vue'
import {
  NButton,
  NDataTable,
  NDatePicker,
  NFlex,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NModal,
  NPagination,
  NSelect,
  NSpace,
  useMessage,
  useDialog,
  type DataTableColumn,
} from 'naive-ui'
import { Tools } from '@/types/Tools'
import { useRouter } from 'vue-router'
const router = useRouter()
const message = useMessage()
const dialog = useDialog()

//#region 查询
const queryLoading = ref(false)
const list = ref([] as Array<TbFootballTeam>)
const queryOrder = ref(1)
const queryList = ref({ tname: '', league: '' } as TbFootballTeam)
const queryPage = ref({ pageNumber: 1, pageSize: 10 } as PageBean)

const queryInfo = ref({
  orderBy: queryOrder,
  tname: queryList.value.tname,
  league: queryList.value.league,
  pageNumber: queryPage.value.pageNumber,
  pageSize: queryPage.value.pageSize,
})

const query = () => {
  queryLoading.value = true
  Api.get('/crud/footballteam', queryInfo.value, (data: BaseDataResult<PageVO<TbFootballTeam>>) => {
    queryLoading.value = false
    if (data.success) {
      list.value = data.data.list
      queryPage.value = data.data.pageBean
      return
    }
    message.error(data.message)
  })
}

onMounted(() => {
  query()
})

const requery = () => {
  queryPage.value.pageNumber = 1
  query()
}

const reset = () => {
  queryOrder.value = 1
  queryInfo.value.tname = ''
  queryInfo.value.league = ''
  requery()
}

// 选择器的选项
const selectOptions = ref({
  value: queryOrder,
  options: [
    {
      label: '粉丝数',
      value: 1,
    },
    {
      label: '联赛冠军数',
      value: 2,
    },
    {
      label: '杯赛冠军数',
      value: 3,
    },
    {
      label: '球队创建时间',
      value: 4,
    },
  ],
})

// datatable的数据
const listColumns = [
  {
    title: '球队名称',
    key: 'tname',
    render(row) {
      return h(
        NButton,
        {
          text: true,
          type: 'info',
          onClick: () => {
            getIntro(row)
          },
        },
        row.tname,
      )
    },
  },
  {
    title: '所属联赛',
    key: 'league',
  },
  {
    title: '联赛冠军数量',
    key: 'champions',
  },
  {
    title: '杯赛冠军数量',
    key: 'cups',
  },
  {
    title: '粉丝数（万）',
    key: 'fans',
  },
  {
    title: '进球数记录',
    key: 'goals',
  },
  {
    title: '进球数记录保持者',
    key: 'gname',
  },
  {
    title: '俱乐部创建时间',
    key: 'created',
    render(row) {
      return h('span', {}, Tools.formatDate(row.created as number, 'yyyy-MM-dd'))
    },
  },
  {
    title: '操作',
    key: 'action',
    render(row) {
      return h(NSpace, {}, [
        h(
          NButton,
          {
            type: 'warning',
            size: 'small',
            onClick: () => {
              getModifyIntro(row)
            },
          },
          '修改',
        ),
        h(
          NButton,
          {
            type: 'error',
            size: 'small',
            onClick: () => {
              showDelete(row)
            },
          },
          '删除',
        ),
      ])
    },
  },
] as Array<DataTableColumn<TbFootballTeam>>

// 查询简介
const introInfo = ref('')
const getIntro = (row: TbFootballTeam) => {
  queryLoading.value = true
  Api.get(`/crud/footballteam/${row.ftid}`, {}, (data: BaseDataResult<TbFootballTeam>) => {
    queryLoading.value = false
    if (data.success) {
      introInfo.value = data.data.intro
      showIntro(row)
      return
    }
    message.error(data.message)
  })
}

const showIntro = (row: TbFootballTeam) => {
  dialog.create({
    title: `${row.tname}简介`,
    content: `${introInfo.value}`,
  })
}

//#endregion

const dateinfo = ref(Tools.formatDate(new Date(), 'yyyy-MM-dd'))
// 时间选择器验证
const dateValidate = (ts: number) => {
  return new Date().getTime() <= ts
}
//#region 添加
const addInfo = ref({} as TbFootballTeam)
const addLoading = ref(false)
const addVisible = ref(false)

const showAdd = () => {
  addInfo.value.tname = ''
  addInfo.value.league = ''
  addInfo.value.intro = ''
  addInfo.value.champions = 0
  addInfo.value.cups = 0
  addInfo.value.fans = 1
  addInfo.value.goals = 1
  addInfo.value.gname = ''
  dateinfo.value = Tools.formatDate(new Date(), 'yyyy-MM-dd')
  addVisible.value = true
}

const add = () => {
  addLoading.value = true
  addInfo.value.created = dateinfo.value
  Api.post('/crud/footballteam', addInfo.value, (data: BaseResult) => {
    addLoading.value = false
    if (data.success) {
      requery()
      addVisible.value = false
      message.success('添加成功')
      return
    }
    message.error(data.message)
  })
}

//#endregion

//#region 修改
const getModifyIntro = (intro: TbFootballTeam) => {
  queryLoading.value = true
  Api.get(`/crud/footballteam/${intro.ftid}`, {}, (data: BaseDataResult<TbFootballTeam>) => {
    queryLoading.value = false
    if (data.success) {
      intro.intro = data.data.intro
      showModify(intro)
      return
    }
    message.error(data.message)
  })
}

const modifyLoading = ref(false)
const modifyInfo = ref({} as TbFootballTeam)
const modifyVisible = ref(false)
const showModify = (row: TbFootballTeam) => {
  modifyInfo.value = Tools.concatJson(row) as TbFootballTeam
  dateinfo.value = Tools.formatDate(row.created as number, 'yyyy-MM-dd')
  modifyVisible.value = true
}

const modify = () => {
  modifyLoading.value = true
  modifyInfo.value.created = dateinfo.value
  Api.put('/crud/footballteam', modifyInfo.value, (data: BaseResult) => {
    modifyLoading.value = false
    if (data.success) {
      modifyVisible.value = false
      message.success('修改成功')
      return
    }
    message.error(data.message)
  })
}

//#endregion

//#region 删除
const showDelete = (row: TbFootballTeam) => {
  dialog.error({
    title: '警告',
    content: `确定删除${row.tname}吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      queryLoading.value = true
      Api.delete(`/crud/footballteam/${row.ftid}`, {}, (data: BaseResult) => {
        queryLoading.value = false
        if (data.success) {
          message.success('删除成功')
          requery()
          return
        }
        message.error(data.message)
      })
    },
  })
}
//#endregion
</script>

<style scoped lang="scss"></style>
